package com.example.myjavafx.service;
import com.example.myjavafx.model.User;
import com.example.myjavafx.model.UserDto;
import com.example.myjavafx.model.Users;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.application.Platform;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.function.Consumer;

public class JavaFXApiService {
//    private static final String BASE_URL = "http://localhost:8080/api";
    private static final String BASE_URL = "http://localhost:8080/api";
    private static final HttpClient CLIENT = HttpClient.newHttpClient();
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    // ... 其他现有方法 ...

    // 异步创建或更新用户
    public static void postUser(User user, Consumer<List<Users>> onSuccess, Consumer<String> onError) throws JsonProcessingException {
        String url = BASE_URL + "/users";
        String requestBody;
//        String requestBody = "{\"id\":12345,\"name\":\"lichuandi\"}";
//        try {
//            // 将User对象序列化为JSON字符串
            requestBody = OBJECT_MAPPER.writeValueAsString(user);
//        } catch (Exception e) {
//            Platform.runLater(() -> onError.accept("序列化失败: " + e.getMessage()));
//            return;
//        }

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json") // 设置请求头
                .POST(HttpRequest.BodyPublishers.ofString(requestBody)) // 设置请求体
                .build();

        //                    if (response.statusCode() == 200 || response.statusCode() == 201) {
        //                        Platform.runLater(() -> onSuccess.accept(null)); // 成功时调用onSuccess
        //                    } else {
        //                        Platform.runLater(() -> onError.accept("服务器响应错误: " + response.statusCode()));
        //                    }
        CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString()) // 对于POST请求，discarding我们可能不关心响应体
                .thenApply(HttpResponse::body)
//                .thenAccept(JavaFXApiService::parseJson)
                .thenAccept(response -> {
//                    List<User> users = parseJson(response);
                    List<Users> users =    UserDto.parseJson(response);
                    Platform.runLater(() -> onSuccess.accept(users));
                })
                .exceptionally(e -> {
                    Platform.runLater(() -> onError.accept("请求失败: " + e.getMessage()));
                    return null;
                });
    }

    // ... 其他现有方法 ...
    @SuppressWarnings("unchecked")
    private static <T> T parseJson1(String json, Class<T> responseType) {
        // 这里应该使用Jackson/Gson等库来解析JSON到指定的类型
        // 由于这是一个示例，我们简单地返回null或抛出异常
        if (responseType == List.class) {
            // 假设我们总是返回User列表（在实际应用中，这应该基于JSON内容动态决定）
//            return (T) List.of(new User("张三", 25), new User("李四", 30));
         return null;
        }
        throw new IllegalArgumentException("不支持的响应类型: " + responseType.getName());
    }
    private static List<Users> parseJson(String json) {
        // 实际项目中使用 Jackson/Gson 等库，这里简化处理
        System.out.println(json + "解析JSON");
        List<Users> users = UserDto.parseJson(json);
//        return List.of(
//                new User("张三", 25),
//                new User("李四", 30)
//        );
        return users;
    }
}